using System.Linq;
using System.Threading.Tasks;
using MongoDB.Driver;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Validation.Handlers.Common;
using Sustainalytics.Synchronization.Validation.Internals;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.Handlers.CorporateGovernance
{
    public class IndicatorHandler : HandlerWithGrouping<GovernanceIndicator>
    {
        public IndicatorHandler(ValidationMongoCollection<GovernanceIndicator> collections)
            : base(collections)
        {
        }

        protected override ProjectionDefinition<GovernanceIndicator> GetProjectionDefinition()
        {
            return
                Builders<GovernanceIndicator>.Projection.Include(x => x.CompanyId)
                    .Include(x => x.Score)
                    .Include(x => x.Number)
                    .Include(x => x.Outlook)
                    .Include(x => x.Comment);
        }
    }


    public class GovernanceCorporateDataLoader
    {
        private readonly IMongoCollection<CorporateData> mongoCollection;
        private readonly CorporateGovernanceCompanies companies;
        private readonly WhiteListCompanies whiteListCompanies;


        public GovernanceCorporateDataLoader(IMongoCollection<CorporateData> mongoCollection, CorporateGovernanceCompanies companies, WhiteListCompanies whiteListCompanies)
        {
            this.mongoCollection = mongoCollection;
            this.companies = companies;
            this.whiteListCompanies = whiteListCompanies;
        }

        public async Task LoadAsync()
        {
            var values = await mongoCollection.Find(Builders<CorporateData>.Filter.Where(x => x.CorporateGovernanceResearchState.ResearchState == ResearchState.ResearchAvailable))
               .Project(x => new
               {
                   Id = x.Id,
                   CapitalIqId = x.CapitalIqId
               }).ToListAsync().ConfigureAwait(false);


            var companiesIds = values.Where(g => !whiteListCompanies.Exists(x => x.CapitalIqId == g.CapitalIqId
                && x.ResearchProduct == BusinessResearchProduct.CorporateGovernance)).Select(x => x.Id);
                
            companies.AddRange(companiesIds);
        }
    }
}